package com.lz.common.timaTask;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lz.servlet.domain.InterfaceCallLog;
import com.lz.servlet.mapper.InterfaceCallLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Set;

import static com.lz.common.baseBean.StaticString.REDIS_HOW_OFTEN;
import static com.lz.common.baseBean.StaticString.REDIS_KEY_SPLIT;

@Service
public class CallCountSyncService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private InterfaceCallLogMapper interfaceCallLogMapper;

    @Scheduled(fixedRate = 5000)
    public void syncToDatabase() {
        Set<String> keys = redisTemplate.keys(REDIS_HOW_OFTEN + REDIS_KEY_SPLIT + "*");
        if (keys == null || keys.isEmpty()) return;

        for (String key : keys) {
            String countStr = redisTemplate.opsForValue().get(key);
            if (countStr == null) continue;

            String[] parts = key.split(REDIS_KEY_SPLIT);
            if (parts.length < 3 || !parts[0].equals(REDIS_HOW_OFTEN)) continue;

            String className = parts[1];
            String methodName = parts[2];
            int count = Integer.parseInt(countStr);

            LambdaQueryWrapper<InterfaceCallLog> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(InterfaceCallLog::getClassName, className);
            wrapper.eq(InterfaceCallLog::getMethodName, methodName);
            InterfaceCallLog existing = interfaceCallLogMapper.selectOne(wrapper);
            InterfaceCallLog logEntry;

            if (existing != null) {
                existing.setCallCount(existing.getCallCount() + count);
                interfaceCallLogMapper.updateById(existing);
            } else {
                logEntry = new InterfaceCallLog();
                logEntry.setClassName(className);
                logEntry.setMethodName(methodName);
                logEntry.setCallCount(count);
                interfaceCallLogMapper.insert(logEntry);
            }

            // 可选：清空 Redis 中已同步的数据
            redisTemplate.delete(key);
        }
    }
}
